import axios, { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import { Loading } from "./helper/loading";

/**
 * 网络请求
 */
class HttpRequest {
  private _service: AxiosInstance;
  constructor(config: AxiosRequestConfig) {
    this._service = axios.create(config);
    const _loading = new Loading();

   /**
		 * HTTP请求拦截器
		 * 客户端发送请求 -> [请求拦截器] -> 服务器
		 * token校验(JWT) : 接受服务器返回的token,存储到redux/本地储存当中
		 */
    this._service.interceptors.request.use(
      (config: AxiosRequestConfig): any => {
        const token: string = '11111';
        _loading.show(); // 打开loading
				return { ...config, headers: { ...config.headers, "Access-Token": token } };
      },
      (error: AxiosError) => {
        console.log(error);
      },
    );

    /**
		 * HTTP响应拦截器
		 * 服务器换返回信息 -> [拦截统一处理] -> 客户端JS获取到信息
		 */
    this._service.interceptors.response.use((response: AxiosResponse) => {
      const { data, config } = response;
      _loading.hide(); // 关闭loading
      console.log(config);
      if (data.code !== 1000) {
        return Promise.reject(data);
      }
      return Promise.resolve(data);
    }, (error: AxiosError) => {
      console.log(error);
      _loading.hide(); // 关闭loading
      return Promise.reject(error);
    })
  }

  public get<T>(url: string, params?: object, options = {}): Promise<T> {
    return this._service.get(url, { params, ...options });
  }

  public post<T>(url: string, params?: object, options = {}): Promise<T> {
    return this._service.post(url, params, options);
  }

  public put<T>(url: string, params?: object, options = {}): Promise<T> {
    return this._service.put(url, params, options);
  }

  public delete<T>(url: string, params?: object, options = {}): Promise<T> {
    return this._service.delete(url, { params, ...options });
  }
}

// const ApiWrap = async (description: string, apiFn: () => void, ...args: any[]) => {
//   let [error, data] = [null, null];
//   try {
//     const result = await apiFn(...args);
//     data = result;
//   } catch (error) {
//     error = error || true;
//   }
//   return Promise.resolve([error, data]);
// }

/**
 * 创建http请求
 */
const createHttpRequest = (() => {
  let _http: HttpRequest;
  return (config: AxiosRequestConfig) => {
    if (!_http) {
      _http = new HttpRequest(config);
    }
    return _http;
  };
})();

export default createHttpRequest({
  baseURL: "localhost:13000",
});
